dojo.provide('app.add');
dojo.require('app.i18n');
dojo.requireLocalization('app.i18n');
dojo.require('app.utils.utils');
dojo.require('app.model');
dojo.require('dijit.form.Textarea');
dojo.require('dijit.form.Form');
dojo.require('app.form.AddressGeoItem');
dojo.require('app.form.FilteringSelect');
dojo.require('app.form.ResultsPane');
dojo.require('app.mvc.View');
dojo
		.declare(
				'app.add',
				[ app.map.utils ],
				{
					_time : 2000,
					_wdgIds : [ 'addNameInput', 'addEmailInput',
							'addHomePhoneInput', 'addCommercialPhoneInput',
							'addCountryInput', 'addStreetInput',
							'addStNumberInput', 'addComplementInput',
							'addZipInput', 'addAddrCountrySelect',
							'addDistritcSelect', 'addStateSelect',
							'addCitySelect', 'addComments',
							'googleAddressInput', 'addConfirmed' ],
					_addrParts : [ 'address.street.description',
							'address.stNumber', 'address.complement',
							'address.district.description',
							'address.city.description',
							'address.state.description',
							'address.country.description' ],
					_add : function(e) {
						var _self = this;
						var arr = this._wdgIds;
						var hidds = new Array();
						dojo.query('input[type=hidden]', 'addForm').forEach(
								function(a) {
									hidds.push(a);
								});
						var confirmed = dijit.byId('addConfirmed').get('value');
						var cnt = app.model.getData(this._wdgIds, hidds);
						if (!cnt['address.description']) {
							cnt['address.description'] = '';
							for (idx in this._addrParts) {
								if (cnt[this._addrParts[idx]]) {
									cnt['address.description'] += (cnt['address.description'].length == 0 ? ''
											: ', ');
									cnt['address.description'] += cnt[this._addrParts[idx]];
								}
							}
						}
						var data = {
							content : cnt,
							load : function(data, io) {
								console.log(data);
							},
							error : function(err, io) {
								console.error(err);
							}
						};

						var endpoint = confirmed ? Services.resident
								: Services.indication;
						return endpoint.Post(data);
					},
					_selectMapAddress : function(gResult) {
						this._setMapPos(gResult);

					},
					geocodeAddress : function(val) {
						if (val && val.length > 0) {
							var _self = this;
							this.geocode({
								'address' : val,
								'load' : function(results) {
									if (results && results.length > 0) {
										dijit.byId('addressPane').set('items',
												results);
										_self._setMapPos(results[0]);
									}
								},
								'error' : function(status) {
									console.log(status);
								}
							});
						}
					},
					onGoogle : function() {
						this.geocodeAddress(dijit.byId('googleAddressInput')
								.get('value'));
					},
					onGoogleError : function() {
						var b = app.i18n.getLocalization('app.i18n');
						dojo.attr('mapContainer', 'innerHTML', b
								.get('google_error'));
						var bt = dojo.byId('reloadGoogleBt')
								|| dojo.create('a', {
									innerHTML : b.get('google_reload')
								}, 'mapContainer');
						var _self = this;
						var conn = dojo.connect(bt, 'onclick', function(e) {
							_self.initGoogle();
							dojo.disconnect(conn);
						});
					},
					startup : function() {
						console.log(this.declaredClass + ' started')
						dojo.parser.parse('addViewContainer');
						var bundle = app.i18n.getLocalization('app.i18n');
						var _self = this;

						var txt_ctor = app.form.SubmitTextBox;
						var sel_ctor = app.form.FilteringSelect;

						function _onChange() {

						}
						;
						function _onSelectChange() {
							if (!this.item)
								return;
							var prop = this.get('name');
							console.group(this.get('name') + '.'
									+ '_onSelectChange');
							var idx = prop.lastIndexOf('.');
							idx = idx < 0 ? prop.length : idx;
							var pck = prop.substring(0, idx);
							var data = app.model.prune(this.item.i, pck);
							for (d in data) {
								var filtered = dojo.query('input',
										'hiddenFields').filter(function(item) {
									var name = dojo.attr(item, 'name');
									return name === d;
								});
								if (filtered.length) {
									dojo.attr(filtered[0], 'value', data[d]);
								}
							}
						}

						function setDValue(value) {
							this.set('value', value);
						}

						new dijit.form.Form({
							id : 'addForm',
							method : 'post'
						}, 'addForm');

						var name = new txt_ctor({
							name : 'contact.name',
							placeHolder : bundle.get('search_placeholder',
									'register_label_name'),
							onChange : _onChange
						}, 'addNameInput');

						var country = new sel_ctor({
							name : 'contact.country.id',
							placeHolder : bundle.get('search_placeholder',
									'register_label_country'),
							store : Services.country.store(),
							labelAttr : 'description',
							searchAttr : 'description',
							ignoreCase : true,
							onChange : _onSelectChange,
							setter : setDValue
						}, 'addCountryInput');

						var email = new txt_ctor({
							name : 'contact.email',
							placeHolder : bundle.get('search_placeholder',
									'contact_label_email'),
							onChange : _onChange
						}, 'addEmailInput');

						var hPhone = new txt_ctor({
							name : 'contact.homePhone',
							placeHolder : bundle.get('search_placeholder',
									'contact_label_home_phone'),
							onChange : _onChange
						}, 'addHomePhoneInput');

						var cPhone = new txt_ctor({
							name : 'contact.commercialPhone',
							placeHolder : bundle.get('search_placeholder',
									'contact_label_com_phone'),
							onChange : _onChange
						}, 'addCommercialPhoneInput');

						var addr = new txt_ctor({
							name : 'address.street.description',
							placeHolder : bundle.get('search_placeholder',
									'register_label_street'),
							onChange : _onChange
						}, 'addStreetInput');

						var stNum = new txt_ctor({
							name : 'address.stNumber',
							placeHolder : bundle.get('search_placeholder',
									'register_label_stNumber'),
							onChange : _onChange
						}, 'addStNumberInput');

						var compl = new txt_ctor({
							name : 'address.complement',
							placeHolder : bundle.get('search_placeholder',
									'register_label_complement'),
							onChange : _onChange
						}, 'addComplementInput');

						var zip = new txt_ctor({
							name : 'address.zip',
							placeHolder : bundle.get('search_placeholder',
									'register_label_zip'),
							onChange : _onChange
						}, 'addZipInput');

						var city = new sel_ctor({
							name : 'address.city.id',
							placeHolder : bundle.get('search_placeholder',
									'register_label_city'),
							store : Services.city.store(),
							labelAttr : 'description',
							searchAttr : 'description',
							ignoreCase : true,
							onChange : _onSelectChange,
							setter : setDValue
						}, 'addCitySelect');

						var district = new sel_ctor({
							name : 'address.district.id',
							placeHolder : bundle.get('search_placeholder',
									'register_label_district'),
							store : Services.district.store(),
							labelAttr : 'description',
							searchAttr : 'description',
							ignoreCase : true,
							onChange : _onSelectChange,
							setter : setDValue
						}, 'addDistritcSelect');

						var state = new sel_ctor({
							name : 'address.state.id',
							placeHolder : bundle.get('search_placeholder',
									'register_label_state'),
							store : Services.state.store(),
							labelAttr : 'description',
							searchAttr : 'description',
							ignoreCase : true,
							onChange : _onSelectChange,
							setter : setDValue
						}, 'addStateSelect');

						var addrCountry = new sel_ctor({
							name : 'address.country.id',
							placeHolder : bundle.get('search_placeholder',
									'register_label_country'),
							store : Services.country.store(),
							labelAttr : 'description',
							searchAttr : 'description',
							ignoreCase : true,
							onChange : _onSelectChange,
							setter : setDValue
						}, 'addAddrCountrySelect');

						var conf = new dijit.form.CheckBox({
							name : 'type',
							value : 'true'
						}, 'addConfirmed');

						var bt = new dijit.form.Button({
							label : bundle.get('add_label'),
							onClick : function(e) {
								console.log('addding')
								_self._add();
							}
						}, 'add');

						var geoBt = new dijit.form.Button({
							label : bundle.get('geocode_label'),
							onClick : function(e) {
								console.log('geocode')
								_self.geocodeAddress(dijit.byId(
										'googleAddressInput').get('value'));
							}
						}, 'geocode');

						var comments = new dijit.form.Textarea({
							name : "comments",
							style : "width:100%;"
						}, "addComments");

						var gAddr = new dijit.form.TextBox({
							name : "search.address",
							onChange : function(e) {
								if (this.geocoder) {
									_self.geocodeAddress(this.get('value'));
								}
							}
						}, 'googleAddressInput');

						new app.form.ResultsPane({
							createItem : function(item, node) {
								new app.form.AddressGeoItem({
									'gResult' : item,
									'onSelectClick' : function(e) {
										_self._selectMapAddress(this.gResult);
									},
									'onViewClick' : function(e) {
										_self._setMapPos(this.gResult);
									}
								}, node);
							}
						}, 'addressPane');

						var view = app.mvc.View.get('add');
						for (id in this._wdgIds) {
							var wdg = dijit.byId(this._wdgIds[id]);
							view.bind({
								widget : wdg
							});
						}

						var setters = {};
						setters['address.district.description'] = function(id,
								val, reset) {
								console.group('Set Node');
								console.log(arguments);
								dojo.attr(id, 'value', val);
								
						};
						setters['address.city.description'] = function(id,
								val, reset) {

						};
						setters['address.state.description'] = function(id,
								val, reset) {

						};
						setters['address.country.description'] = function(id,
								val, reset) {

						};

						dojo.query('input[type=hidden]', 'hiddenFields')
								.forEach(function(item) {
									view.bind({
										node : item
									});
								})
						this.initGoogle();
						console.log(this.declaredClass + ' loaded');

					}
				});

app.add.page = new app.add();